package com.linzelin.controller;


import com.linzelin.po.Books;
import com.linzelin.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
@RequestMapping("/Book")
public class BookController {
    //创建service的对象
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;


    //查询全部的数据并返回对应的展示页面
    @RequestMapping("/allBook")
    public String allBook(Model model) {
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("allBooks", list);
        return "allBook";
    }


    @RequestMapping(value = "/addBook", method = RequestMethod.POST)
    public String addBook(Books books, Model model) {
        int i = bookService.addBook(books);
        if (i > 0) {
            model.addAttribute("msg", "添加成功");
        } else {
            model.addAttribute("msg", "添加失败");
        }
        System.out.println(books);
        return "forward:/Book/allBook";
    }

    @RequestMapping("/updateBookPage/{id}")
    public String updateBookPage(@PathVariable int id, Model model) {
        model.addAttribute("book", bookService.queryBookById(id));
        return "updateBook";
    }

    @RequestMapping(value = "/updateBook")
    public String updateBook(Books book, Model model) {
        int i = bookService.updateBook(book);
        if (i > 0) {
            model.addAttribute("msg", "修改成功");
        } else {
            model.addAttribute("msg", "修改失败");
        }
        return "forward:/Book/allBook";
    }

    @RequestMapping("/deleteBook/{id}")
    public String deleteBook(@PathVariable int id, Model model) {
        if (bookService.deleteBookById(id) > 0) {
            model.addAttribute("msg", "删除成功");
        } else {
            model.addAttribute("msg", "删除失败");
        }
        return "forward:/Book/allBook";
    }

    @RequestMapping("/findBook")
    public String findBook(String find, Model model) {
        model.addAttribute("findContext", find);
        model.addAttribute("allBooks", bookService.findBoook(find));
        return "allBook";
    }

}
